<template>
  <div class="login">
    <LoginLeftView></LoginLeftView>

    <div class="right-wrap">
      <div class="top-right-wrap">
        <div class="btn theme-btn" @click="toggleTheme">
          <i class="iconfont-sys">
            {{ isDark ? '&#xe6b5;' : '&#xe725;' }}
          </i>
        </div>
        <ElDropdown @command="changeLanguage" popper-class="langDropDownStyle">
          <div class="btn language-btn">
            <i class="iconfont-sys icon-language">&#xe611;</i>
          </div>
          <template #dropdown>
            <ElDropdownMenu>
              <div v-for="lang in languageOptions" :key="lang.value" class="lang-btn-item">
                <ElDropdownItem
                  :command="lang.value"
                  :class="{ 'is-selected': locale === lang.value }"
                >
                  <span class="menu-txt">{{ lang.label }}</span>
                  <i v-if="locale === lang.value" class="iconfont-sys icon-check">&#xe621;</i>
                </ElDropdownItem>
              </div>
            </ElDropdownMenu>
          </template>
        </ElDropdown>
      </div>
      <div class="header">
        <ArtLogo class="icon" />
        <h1>{{ systemName }}</h1>
      </div>
      <div class="login-wrap">
        <div class="form">
          <h3 class="title">{{ $t('login.title') }}</h3>
          <p class="sub-title">{{ $t('login.subTitle') }}</p>
          <ElForm
            ref="formRef"
            :model="formData"
            :rules="rules"
            @keyup.enter="handleSubmit"
            style="margin-top: 25px"
          >
            <ElFormItem prop="username">
              <ElInput :placeholder="$t('login.placeholder[0]')" v-model.trim="formData.username" />
            </ElFormItem>
            <ElFormItem prop="password">
              <ElInput
                :placeholder="$t('login.placeholder[1]')"
                v-model.trim="formData.password"
                type="password"
                radius="8px"
                autocomplete="off"
                show-password
              />
            </ElFormItem>

            <div class="forget-password">
              <ElCheckbox v-model="formData.rememberPassword">{{
                $t('login.rememberPwd')
              }}</ElCheckbox>
              <RouterLink :to="RoutesAlias.ForgetPassword">{{ $t('login.forgetPwd') }}</RouterLink>
            </div>

            <div style="margin-top: 30px">
              <ElButton
                class="login-btn"
                type="primary"
                @click="handleSubmit"
                :loading="loading"
                v-ripple
              >
                {{ $t('login.btnText') }}
              </ElButton>
            </div>

            <div class="footer">
              <p>
                {{ $t('login.noAccount') }}
                <RouterLink :to="RoutesAlias.Register">{{ $t('login.register') }}</RouterLink>
              </p>
            </div>
          </ElForm>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
  import dayjs from 'dayjs'
  import AppConfig from '@/config'
  import { RoutesAlias } from '@/router/routesAlias'
  import { ElNotification, ElMessage } from 'element-plus'
  import { useUserStore } from '@/store/modules/user'

  import { languageOptions } from '@/locales'
  import { LanguageEnum, SystemThemeEnum } from '@/enums/appEnum'
  import { CHE_JIAN_ID } from '@/utils/constants'
  import { useI18n } from 'vue-i18n'
  import { HttpError } from '@/utils/http/error'
  import { useGo } from '@/composables/useGo'

  import { allGongXu, getBanCiXinXi } from '@/api/gongGongChaXun'
  import { getHuoQuCaiJiList } from '@/api/shengChanJianShi'
  import { getHuoQuRenYuanJiBenXinXi, loginAndToken } from '@/api/account'
  import { getyongHuZhanShiCaiDan } from '@/api/quanXianGuanLi'
  import { getBaoCunSheZhiCanShu } from '@/api/shengChanJianShi'
  import { getHuoQuYongHuMingCheng } from '@/api/role'

  defineOptions({ name: 'Login' })

  const { t } = useI18n()
  import { useSettingStore } from '@/store/modules/setting'
  import type { FormInstance, FormRules } from 'element-plus'

  type AccountKey = 'super' | 'admin' | 'user'

  export interface Account {
    key: AccountKey
    label: string
    userName: string
    password: string
    roles: string[]
  }

  const { go } = useGo()

  const settingStore = useSettingStore()
  const { isDark, systemThemeType } = storeToRefs(settingStore)

  const userStore = useUserStore()
  const quanXianList = ref<string[]>([])

  const systemName = AppConfig.systemInfo.name
  const formRef = ref<FormInstance>()

  const formData = reactive({
    username: '',
    password: '',
    rememberPassword: true
  })

  const rules = computed<FormRules>(() => ({
    username: [{ required: true, message: t('login.placeholder[0]'), trigger: 'blur' }],
    password: [{ required: true, message: t('login.placeholder[1]'), trigger: 'blur' }]
  }))

  const loading = ref(false)

  // 登录
  const handleSubmit = async () => {
    if (!formRef.value) return

    try {
      // 表单验证
      const valid = await formRef.value.validate()
      if (!valid) return

      loading.value = true

      // 登录请求
      const { username, password } = formData

      const data = {
        client_id: 'basic-web',
        client_secret: '1q2w3e*',
        grant_type: 'password',
        username,
        password
      }

      const res = await loginAndToken(data)
        .then((res) => res)
        .catch((error) => {
          console.log(error)
          const errorTitle = error.data.error_description
          if (
            errorTitle ===
            'The user account has been locked out due to invalid login attempts. Please wait a while and try again.'
          ) {
            ElMessage.error(t('httpMsg.IllegalLogin'))
          } else {
            ElMessage.error(t('httpMsg.accountOrPasswordIncorrect'))
          }

          throw error
        })

      const { access_token, refresh_token } = res

      // 验证token
      if (!access_token) {
        throw new Error('Login failed - no token received')
      }

      // 存储token和用户信息
      userStore.setToken(access_token, refresh_token)
      userStore.setLoginStatus(true)

      // 设置车间id 功能未知
      userStore.setSysConstant('cheJianID', CHE_JIAN_ID)

      Promise.all([getGongYiJieDianList(), getUserInfo(), getMenu()]).then(() => {
        // 如果有可视化权限,跳转到可视化
        if (
          quanXianList.value.findIndex((val) => {
            return val == '70000'
          }) !== -1
        ) {
          userStore.goHome()
        } else {
          // 没有,跳转到选项列表第一个
          let minNum = quanXianList.value[0]
          quanXianList.value.forEach((val, index) => {
            if (val < quanXianList.value[index + 1] && val < minNum && val.length === 5) {
              minNum = val
            }
          })
          // menuClick(minNum)
        }
      })

      // 登录成功后 获取 实时数据keys集合
      getValueKeysList()

      // 获取区域
      getQuYuNum()

      // 登录成功处理
      showLoginSuccessNotice()
    } catch (error) {
      // 处理 HttpError
      if (error instanceof HttpError) {
        // console.log(error.code)
      } else {
        // 处理非 HttpError
        ElMessage.error('登录失败，请稍后重试')
        console.error('[Login] Unexpected error:', error)
      }
    } finally {
      loading.value = false
    }
  }

  // 获取工艺节点id
  async function getGongYiJieDianList() {
    await allGongXu().then((res) => {
      for (let value of res) {
        if (value.name === '细纱') {
          userStore.setSysConstant('xiShaID', value.id)
          let data = {
            CraftNodeID: value.id,
            dateTime: dayjs().format('YYYY-MM-DD HH:mm:ss')
          }
          getClassesInfo(data)
        } else if (value.name === '粗纱') {
          userStore.setSysConstant('cuShaID', value.id)
        } else if (value.name === '粗细联') {
          userStore.setSysConstant('cuXiLianID', value.id)
        } else if (value.name === '络筒') {
          userStore.setSysConstant('luoTongID', value.id)
        } else if (value.name === '末并') {
          userStore.setSysConstant('moBingID', value.id)
        } else if (value.name === '精梳') {
          userStore.setSysConstant('jingShuID', value.id)
        } else if (value.name === '条卷') {
          userStore.setSysConstant('tiaoJuanID', value.id)
        } else if (value.name === '预并') {
          userStore.setSysConstant('yuBingID', value.id)
        } else if (value.name === '二并') {
          userStore.setSysConstant('erBingID', value.id)
        } else if (value.name === '梳棉') {
          userStore.setSysConstant('shuMianID', value.id)
        } else if (value.name === '异纤') {
          userStore.setSysConstant('yiXianID', value.id)
        } else if (value.name === '开棉') {
          userStore.setSysConstant('kaiMianID', value.id)
        } else if (value.name === '混棉') {
          userStore.setSysConstant('hongMianID', value.id)
        } else if (value.name === '抓棉') {
          userStore.setSysConstant('zhuaMianID', value.id)
        }
      }
    })
  }

  // 获取用户信息
  async function getUserInfo() {
    await getHuoQuRenYuanJiBenXinXi().then(async (res) => {
      const userInfo = res
      userStore.setSysConstant('jueSeName', res.roles[0])
      userStore.setSysConstant('userID', res.id)
      // 如果当前登录用户的角色是admin，则需要在该返回数组的基础上增加权限管理相关页面的code
      if (
        res.roles.findIndex((val) => {
          return val === 'admin'
        }) !== -1
      ) {
        quanXianList.value.push('10000', '17000', '17100', '17200')
      }

      // 旧系统又专门发了一个接口拿名字
      await getHuoQuYongHuMingCheng(res.id).then((res) => {
        userInfo.name = res.name
        userStore.setUserInfo(userInfo)
      })
    })
  }

  // 获取菜单权限
  async function getMenu() {
    await getyongHuZhanShiCaiDan()
      .then((res) => {
        quanXianList.value.push(...res)
        userStore.setSysConstant('quanXian', quanXianList.value)
      })
      .catch(() => {})
  }

  // 根据工艺节点、时间，获取上一个班次的班次信息(工序id)
  async function getClassesInfo(data) {
    getBanCiXinXi(data).then((res) => {
      let resJson = res
      let End = dayjs(resJson.end).format('YYYY-MM-DD')
      userStore.setSysConstant('Tsid', resJson.tsId)
      userStore.setSysConstant('Begin', End)
      userStore.setSysConstant('End', resJson.end)
      userStore.setSysConstant('banCi', resJson.shiftName)
    })
  }

  // 登录成功提示
  const showLoginSuccessNotice = () => {
    setTimeout(() => {
      ElNotification({
        title: t('login.success.title'),
        type: 'success',
        duration: 2500,
        zIndex: 10000,
        message: `${t('login.success.message')}, ${systemName}!`
      })
    }, 150)
  }

  const getValueKeysList = () => {
    getHuoQuCaiJiList().then((res) => {
      let key = JSON.stringify(res)
      // localStorage.setItem('valueKeys', key)
      userStore.setSysConstant('valueKeys', key)
    })
  }

  // 获取区域
  const getQuYuNum = () => {
    getBaoCunSheZhiCanShu({ featureKey: '换班模式' }).then((res) => {
      userStore.setSysConstant('quYuNum', res)
    })

    // getBaoCunSheZhiCanShu({ featureKey: '落纱达标值' }).then((res) => {
    //   userStore.setSysConstant('quYuNum_laoShaDaBiaoZhi', res)
    // })
  }

  // 切换语言
  const { locale } = useI18n()

  const changeLanguage = (lang: LanguageEnum) => {
    if (locale.value === lang) return
    locale.value = lang
    userStore.setLanguage(lang)
  }

  // 切换主题
  import { useTheme } from '@/composables/useTheme'
  // import { error } from 'console'

  const toggleTheme = () => {
    let { LIGHT, DARK } = SystemThemeEnum
    useTheme().switchThemeStyles(systemThemeType.value === LIGHT ? DARK : LIGHT)
  }
</script>

<style lang="scss" scoped>
  @use './index';
</style>
